<template>
  <div class="login">
    <!-- model属性用于存放表单的数据对象 -->
    <!-- 给el-form组件添加ref属性，用来获取dom属性 -->
    <el-form :model="loginForm" class="container" :rules="myLoginRules" ref="loginRef">
      <el-form-item>
        <img src="@/assets/snipaste_20190212_204141.png" class="avatar">
      </el-form-item>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" prefix-icon="myicon myicon-user"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <!-- 给原生的dom元素绑定时间是不需要.netive修饰符，如果给组件绑定事件，就必须使用.native修饰符 -->
        <el-input v-model="loginForm.password" type="password" prefix-icon="myicon myicon-key" @keydown.enter.native="handleLogin"></el-input>
      </el-form-item>
      <!-- 给登录按钮添加属性 -->
      <el-form-item>
        <el-button type="primary" class="login-btn" @click="handleLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { login } from '@/api'
export default {
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      myLoginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleLogin () {
      this.$refs.loginRef.validate((isPass) => {
        if (isPass) {
          // axios.post('http://localhost:8888/api/private/v1/login', this.loginForm)
          login(this.loginForm)
            .then(res => {
              if (res.data.meta.status === 200) {
                // 跳转首页
                localStorage.setItem('mytoken', res.data.data.token)
                localStorage.setItem('username', res.data.data.username)
                this.$router.push({ name: 'home' })
              } else {
                // 弹出提示框
                this.$message.error(res.data.meta.msg)
              }
            })
          // console.log('发送')
        } else {
          this.$message.error('校验未通过，重新输入')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.login {
  position: fixed;
  width: 100%;
  height: 100%;
  background-color: #2f4050;

  .container {
    position: absolute;
    left: 0;
    right: 0;
    width: 400px;
    padding: 0px 40px 15px 40px;
    margin: 200px auto;
    background: white;
    .avatar {
      position: relative;
      left: 50%;
      width: 120px;
      height: 120px;
      margin-left: -60px;
      margin-top: -60px;
      box-sizing: border-box;
      border-radius: 50%;
      border: 10px solid #fff;
      box-shadow: 0 1px 5px #ccc;
      overflow: hidden;
    }
    .login-btn {
      width: 100%;
    }
  }
}
</style>
